﻿#include "chatDataBase.h"
#include <iostream>
#include <string.h>
#include <cassert>

using namespace std;


// 构造函数实现
ChatDataBase::ChatDataBase() {

}

// 析构函数实现
ChatDataBase::~ChatDataBase() {
	mysql_close(mysql);
}

// 数据库连接函数实现
void ChatDataBase::connectToDataBase(const char* dbName) {
	mysql = mysql_init(NULL);
	// 通过 mysql_real_connect 函数连接数据库
	mysql = mysql_real_connect(mysql, "47.113.147.178", "group", "admin", dbName, 0, NULL, 0);
	assert(mysql != NULL);  // 连接不成功时直接退出程序
	cout << "Connected to database successfully" << endl;
}

int ChatDataBase::getGroupNamesFromDataBase(string* groupNames) {
	// 设置 UTF-8 编码
	if (mysql_query(mysql, "set names utf8;") != 0) {
		cout << "mysql_query error" << endl;
	}

	// 查询所有表名（群组名）
	if (mysql_query(mysql, "show tables;") != 0) {
		cout << "mysql_query error" << endl;
	}

	// 存储查询结果
	MYSQL_RES* res = mysql_store_result(mysql);
	assert(res != NULL);  // 查询结果为空，直接退出程序

	int count = 0;
	MYSQL_ROW row;
	while ((row = mysql_fetch_row(res)) != NULL) {
		groupNames[count] += row[0]; // 将群组名存入数组中
		count++;
	}
	return count;
}

// 获取群组成员函数实现
void ChatDataBase::getGroupMembersFromDataBase(string groupName, string& groupMembers) {
	char sql[1024] = { 0 };
	sprintf(sql, "select member from %s;", groupName.c_str());

	// 查询表（群组）中的成员
	if (mysql_query(mysql, sql) != 0) {
		cout << "mysql_query - select member error" << endl;
	}

	// 存储查询结果
	MYSQL_RES* res = mysql_store_result(mysql);
	if (res == NULL) {
		cout << "mysql_store_result error" << endl;
	}

	MYSQL_ROW row = mysql_fetch_row(res);
	groupMembers += row[0];// 将群组成员存入字符串中
}

bool ChatDataBase::isUserExist(string userName) {
	// 设置 UTF-8 编码
	if (mysql_query(mysql, "set names utf8;") != 0) {
		cout << "mysql_query error" << endl;
	}

	char sql[128] = { 0 };
	sprintf(sql, "show tables like '%s';", userName.c_str());
	if (mysql_query(mysql, sql) != 0) {
		cout << "mysql_query error" << endl;
	}

	MYSQL_RES* res = mysql_store_result(mysql);
	MYSQL_ROW row = mysql_fetch_row(res);
	if (row == NULL) {// 用户不存在
		return false;
	}
	else {// 用户存在
		return true;
	}
}

void ChatDataBase::userPassword(string userName, string password) {
	char sql[128] = { 0 };
	sprintf(sql, "create table '%s' (password varchar(16), friend varchar(4096));",
		userName.c_str());
	if (mysql_query(mysql, sql) != 0) {
		cout << "mysql_query error" << endl;
	}

	memset(sql, 0, sizeof(sql));
	sprintf(sql, "insert into '%s' (password) values ('%s');",
		userName.c_str(), password.c_str());
	if (mysql_query(mysql, sql) != 0) {
		cout << "mysql_query error" << endl;
	}
}

void ChatDataBase::disconnectToDataBase() {
	//mysql_close(mysql);
}

